//! 负载均衡算法实现

use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
use std::collections::hash_map::DefaultHasher;
use async_trait::async_trait;

use crate::load_balancer::config::BackendConfig;

/// 选择上下文扩展实现
impl SelectionContext {
    /// 创建带有客户端IP的上下文
    pub fn with_client_ip(client_ip: &str) -> Self {
        Self {
            client_ip: Some(client_ip.to_string()),
            ..Default::default()
        }
    }

    /// 创建带有会话ID的上下文
    pub fn with_session_id(session_id: &str) -> Self {
        Self {
            session_id: Some(session_id.to_string()),
            ..Default::default()
        }
    }
}

/// 后端服务器状态
#[derive(Debug, Clone)]
pub struct Backend {
    /// 配置信息
    pub config: BackendConfig,
    /// 当前连接数
    pub active_connections: Arc<AtomicUsize>,
    /// 总请求数
    pub total_requests: Arc<AtomicUsize>,
    /// 成功请求数
    pub successful_requests: Arc<AtomicUsize>,
    /// 平均响应时间
    pub avg_response_time: Arc<std::sync::RwLock<Duration>>,
    /// 最后健康检查时间
    pub last_health_check: Arc<std::sync::RwLock<Instant>>,
    /// 是否健康
    pub is_healthy: Arc<std::sync::RwLock<bool>>,
    /// 当前负载（0.0-1.0）
    pub current_load: Arc<std::sync::RwLock<f64>>,
}

impl Backend {
    /// 创建新的后端服务器
    pub fn new(config: BackendConfig) -> Self {
        Self {
            config,
            active_connections: Arc::new(AtomicUsize::new(0)),
            total_requests: Arc::new(AtomicUsize::new(0)),
            successful_requests: Arc::new(AtomicUsize::new(0)),
            avg_response_time: Arc::new(std::sync::RwLock::new(Duration::from_millis(0))),
            last_health_check: Arc::new(std::sync::RwLock::new(Instant::now())),
            is_healthy: Arc::new(std::sync::RwLock::new(true)),
            current_load: Arc::new(std::sync::RwLock::new(0.0)),
        }
    }

    /// 增加连接数
    pub fn add_connection(&self) {
        self.active_connections.fetch_add(1, Ordering::Relaxed);
    }

    /// 减少连接数
    pub fn remove_connection(&self) {
        self.active_connections.fetch_sub(1, Ordering::Relaxed);
    }

    /// 记录请求
    pub fn record_request(&self, success: bool, response_time: Duration) {
        self.total_requests.fetch_add(1, Ordering::Relaxed);
        if success {
            self.successful_requests.fetch_add(1, Ordering::Relaxed);
        }
        
        // 更新平均响应时间（简化的移动平均）
        if let Ok(mut avg) = self.avg_response_time.write() {
            *avg = Duration::from_nanos(
                (avg.as_nanos() as f64 * 0.9 + response_time.as_nanos() as f64 * 0.1) as u64
            );
        }
    }

    /// 获取当前连接数
    pub fn connection_count(&self) -> usize {
        self.active_connections.load(Ordering::Relaxed)
    }

    /// 获取成功率
    pub fn success_rate(&self) -> f64 {
        let total = self.total_requests.load(Ordering::Relaxed);
        let successful = self.successful_requests.load(Ordering::Relaxed);
        
        if total == 0 {
            1.0
        } else {
            successful as f64 / total as f64
        }
    }

    /// 检查是否健康
    pub fn is_healthy(&self) -> bool {
        match self.is_healthy.read() {
            Ok(guard) => *guard,
            Err(_) => true,
        }
    }

    /// 设置健康状态
    pub fn set_healthy(&self, healthy: bool) {
        if let Ok(mut health) = self.is_healthy.write() {
            *health = healthy;
        }
    }

    /// 获取当前负载
    pub fn get_load(&self) -> f64 {
        match self.current_load.read() {
            Ok(guard) => *guard,
            Err(_) => 0.0,
        }
    }

    /// 更新负载
    pub fn update_load(&self, load: f64) {
        if let Ok(mut current_load) = self.current_load.write() {
            *current_load = load.clamp(0.0, 1.0);
        }
    }
}

/// 负载均衡算法特征
#[async_trait]
pub trait LoadBalancingAlgorithm: Send + Sync {
    /// 选择后端服务器
    async fn select_backend<'a>(&self, backends: &'a [Backend], context: &SelectionContext) -> Option<&'a Backend>;
    
    /// 算法名称
    fn name(&self) -> &'static str;
    
    /// 重置算法状态（如果需要）
    fn reset(&self) {}
}

/// 选择上下文
#[derive(Debug, Clone)]
pub struct SelectionContext {
    /// 客户端IP
    pub client_ip: Option<String>,
    /// 请求路径
    pub path: Option<String>,
    /// 会话ID
    pub session_id: Option<String>,
    /// 自定义哈希键
    pub hash_key: Option<String>,
    /// 请求头
    pub headers: HashMap<String, String>,
    /// 请求大小
    pub request_size: Option<u64>,
}

impl Default for SelectionContext {
    fn default() -> Self {
        Self {
            client_ip: None,
            path: None,
            session_id: None,
            hash_key: None,
            headers: HashMap::new(),
            request_size: None,
        }
    }
}

/// 轮询算法
pub struct RoundRobinAlgorithm {
    current_index: AtomicUsize,
}

impl RoundRobinAlgorithm {
    pub fn new() -> Self {
        Self {
            current_index: AtomicUsize::new(0),
        }
    }
}

#[async_trait]
impl LoadBalancingAlgorithm for RoundRobinAlgorithm {
    async fn select_backend<'a>(&self, backends: &'a [Backend], _context: &SelectionContext) -> Option<&'a Backend> {
        let healthy_backends: Vec<_> = backends.iter().filter(|b| b.is_healthy()).collect();
        
        if healthy_backends.is_empty() {
            return None;
        }
        
        let index = self.current_index.fetch_add(1, Ordering::Relaxed) % healthy_backends.len();
        Some(healthy_backends[index])
    }
    
    fn name(&self) -> &'static str {
        "round_robin"
    }
    
    fn reset(&self) {
        self.current_index.store(0, Ordering::Relaxed);
    }
}

/// 加权轮询算法
pub struct WeightedRoundRobinAlgorithm {
    current_weights: Arc<std::sync::RwLock<HashMap<String, i32>>>,
}

impl WeightedRoundRobinAlgorithm {
    pub fn new() -> Self {
        Self {
            current_weights: Arc::new(std::sync::RwLock::new(HashMap::new())),
        }
    }
}

#[async_trait]
impl LoadBalancingAlgorithm for WeightedRoundRobinAlgorithm {
    async fn select_backend<'a>(&self, backends: &'a [Backend], _context: &SelectionContext) -> Option<&'a Backend> {
        let healthy_backends: Vec<_> = backends.iter().filter(|b| b.is_healthy()).collect();
        
        if healthy_backends.is_empty() {
            return None;
        }
        
        let mut weights = self.current_weights.write().ok()?;
        
        // 计算总权重
        let total_weight: i32 = healthy_backends.iter().map(|b| b.config.weight as i32).sum();
        
        // 更新当前权重
        for backend in &healthy_backends {
            let current = weights.entry(backend.config.id.clone()).or_insert(0);
            *current += backend.config.weight as i32;
        }
        
        // 选择权重最高的后端
        let selected = healthy_backends.iter().max_by_key(|b| {
            weights.get(&b.config.id).copied().unwrap_or(0)
        })?;
        
        // 减少选中后端的权重
        if let Some(weight) = weights.get_mut(&selected.config.id) {
            *weight -= total_weight;
        }
        
        Some(selected)
    }
    
    fn name(&self) -> &'static str {
        "weighted_round_robin"
    }
    
    fn reset(&self) {
        if let Ok(mut weights) = self.current_weights.write() {
            weights.clear();
        }
    }
}

/// 最少连接算法
pub struct LeastConnectionsAlgorithm;

impl LeastConnectionsAlgorithm {
    pub fn new() -> Self {
        Self
    }
}

#[async_trait]
impl LoadBalancingAlgorithm for LeastConnectionsAlgorithm {
    async fn select_backend<'a>(&self, backends: &'a [Backend], _context: &SelectionContext) -> Option<&'a Backend> {
        backends
            .iter()
            .filter(|b| b.is_healthy())
            .min_by_key(|b| b.connection_count())
    }
    
    fn name(&self) -> &'static str {
        "least_connections"
    }
}

/// 加权最少连接算法
pub struct WeightedLeastConnectionsAlgorithm;

impl WeightedLeastConnectionsAlgorithm {
    pub fn new() -> Self {
        Self
    }
}

#[async_trait]
impl LoadBalancingAlgorithm for WeightedLeastConnectionsAlgorithm {
    async fn select_backend<'a>(&self, backends: &'a [Backend], _context: &SelectionContext) -> Option<&'a Backend> {
        backends
            .iter()
            .filter(|b| b.is_healthy())
            .min_by(|a, b| {
                let ratio_a = a.connection_count() as f64 / a.config.weight as f64;
                let ratio_b = b.connection_count() as f64 / b.config.weight as f64;
                ratio_a.partial_cmp(&ratio_b).unwrap_or(std::cmp::Ordering::Equal)
            })
    }
    
    fn name(&self) -> &'static str {
        "weighted_least_connections"
    }
}

/// IP哈希算法
pub struct IpHashAlgorithm;

impl IpHashAlgorithm {
    pub fn new() -> Self {
        Self
    }
    
    fn hash_string(s: &str) -> u64 {
        let mut hasher = DefaultHasher::new();
        s.hash(&mut hasher);
        hasher.finish()
    }
}

#[async_trait]
impl LoadBalancingAlgorithm for IpHashAlgorithm {
    async fn select_backend<'a>(&self, backends: &'a [Backend], context: &SelectionContext) -> Option<&'a Backend> {
        let healthy_backends: Vec<_> = backends.iter().filter(|b| b.is_healthy()).collect();
        
        if healthy_backends.is_empty() {
            return None;
        }
        
        let hash_key = context.client_ip.as_deref().unwrap_or("unknown");
        let hash = Self::hash_string(hash_key);
        let index = hash as usize % healthy_backends.len();
        
        Some(healthy_backends[index])
    }
    
    fn name(&self) -> &'static str {
        "ip_hash"
    }
}

/// 随机算法
pub struct RandomAlgorithm;

impl RandomAlgorithm {
    pub fn new() -> Self {
        Self
    }
}

#[async_trait]
impl LoadBalancingAlgorithm for RandomAlgorithm {
    async fn select_backend<'a>(&self, backends: &'a [Backend], _context: &SelectionContext) -> Option<&'a Backend> {
        let healthy_backends: Vec<_> = backends.iter().filter(|b| b.is_healthy()).collect();
        
        if healthy_backends.is_empty() {
            return None;
        }
        
        let index = rand::random::<usize>() % healthy_backends.len();
        Some(healthy_backends[index])
    }
    
    fn name(&self) -> &'static str {
        "random"
    }
}

/// 最短响应时间算法
pub struct LeastResponseTimeAlgorithm;

impl LeastResponseTimeAlgorithm {
    pub fn new() -> Self {
        Self
    }
}

#[async_trait]
impl LoadBalancingAlgorithm for LeastResponseTimeAlgorithm {
    async fn select_backend<'a>(&self, backends: &'a [Backend], _context: &SelectionContext) -> Option<&'a Backend> {
        let mut min_backend = None;
        let mut min_time = Duration::from_secs(u64::MAX);
        
        for backend in backends.iter().filter(|b| b.is_healthy()) {
            let response_time = match backend.avg_response_time.read() {
                Ok(guard) => *guard,
                Err(_) => Duration::from_millis(0),
            };
            if response_time < min_time {
                min_time = response_time;
                min_backend = Some(backend);
            }
        }
        
        min_backend
    }
    
    fn name(&self) -> &'static str {
        "least_response_time"
    }
}

/// 资源感知算法
pub struct ResourceAwareAlgorithm;

impl ResourceAwareAlgorithm {
    pub fn new() -> Self {
        Self
    }
    
    fn calculate_score(backend: &Backend) -> f64 {
        let load = backend.get_load();
        let success_rate = backend.success_rate();
        let connection_ratio = backend.connection_count() as f64 / backend.config.max_connections as f64;
        
        // 综合评分：成功率权重40%，负载权重35%，连接占用权重25%
        success_rate * 0.4 + (1.0 - load) * 0.35 + (1.0 - connection_ratio) * 0.25
    }
}

#[async_trait]
impl LoadBalancingAlgorithm for ResourceAwareAlgorithm {
    async fn select_backend<'a>(&self, backends: &'a [Backend], _context: &SelectionContext) -> Option<&'a Backend> {
        backends
            .iter()
            .filter(|b| b.is_healthy())
            .max_by(|a, b| {
                let score_a = Self::calculate_score(a);
                let score_b = Self::calculate_score(b);
                score_a.partial_cmp(&score_b).unwrap_or(std::cmp::Ordering::Equal)
            })
    }
    
    fn name(&self) -> &'static str {
        "resource_aware"
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::load_balancer::config::ResourceCapacity;
    use std::net::SocketAddr;

    fn create_test_backend(id: &str, weight: u32) -> Backend {
        let mut config = BackendConfig::default();
        config.id = id.to_string();
        config.weight = weight;
        config.address = "127.0.0.1:8080".parse::<SocketAddr>().unwrap();
        config.capacity = ResourceCapacity::default();
        
        Backend::new(config)
    }

    fn create_test_backends_with_different_specs() -> Vec<Backend> {
        vec![
            {
                let mut config = BackendConfig::default();
                config.id = "low-spec".to_string();
                config.weight = 100;
                config.address = "127.0.0.1:8080".parse().unwrap();
                config.max_connections = 50;
                config.capacity.cpu_cores = 2;
                config.capacity.memory_mb = 1024;
                Backend::new(config)
            },
            {
                let mut config = BackendConfig::default();
                config.id = "high-spec".to_string();
                config.weight = 200;
                config.address = "127.0.0.1:8081".parse().unwrap();
                config.max_connections = 200;
                config.capacity.cpu_cores = 8;
                config.capacity.memory_mb = 8192;
                Backend::new(config)
            },
        ]
    }

    #[tokio::test]
    async fn test_round_robin_algorithm() {
        let algorithm = RoundRobinAlgorithm::new();
        let backends = vec![
            create_test_backend("backend1", 100),
            create_test_backend("backend2", 100),
            create_test_backend("backend3", 100),
        ];
        let context = SelectionContext::default();

        // 测试轮询顺序
        let selected1 = algorithm.select_backend(&backends, &context).await;
        let selected2 = algorithm.select_backend(&backends, &context).await;
        let selected3 = algorithm.select_backend(&backends, &context).await;
        let selected4 = algorithm.select_backend(&backends, &context).await;

        assert!(selected1.is_some());
        assert!(selected2.is_some());
        assert!(selected3.is_some());
        assert!(selected4.is_some());
        
        // 第四次选择应该回到第一个
        assert_eq!(selected1.unwrap().config.id, selected4.unwrap().config.id);
    }

    #[tokio::test]
    async fn test_least_connections_algorithm() {
        let algorithm = LeastConnectionsAlgorithm::new();
        let backends = vec![
            create_test_backend("backend1", 100),
            create_test_backend("backend2", 100),
            create_test_backend("backend3", 100),
        ];
        
        // 模拟不同的连接数
        backends[1].add_connection();
        backends[1].add_connection();
        backends[2].add_connection();

        let context = SelectionContext::default();
        let selected = algorithm.select_backend(&backends, &context).await;

        assert!(selected.is_some());
        // 应该选择连接数最少的 backend1
        assert_eq!(selected.unwrap().config.id, "backend1");
    }

    #[tokio::test]
    async fn test_ip_hash_algorithm() {
        let algorithm = IpHashAlgorithm::new();
        let backends = vec![
            create_test_backend("backend1", 100),
            create_test_backend("backend2", 100),
            create_test_backend("backend3", 100),
        ];

        let mut context = SelectionContext::default();
        context.client_ip = Some("192.168.1.100".to_string());

        let selected1 = algorithm.select_backend(&backends, &context).await;
        let selected2 = algorithm.select_backend(&backends, &context).await;

        assert!(selected1.is_some());
        assert!(selected2.is_some());
        
        // 同一IP应该选择同一个后端
        assert_eq!(selected1.unwrap().config.id, selected2.unwrap().config.id);
    }

    #[tokio::test]
    async fn test_weighted_round_robin_algorithm() {
        let algorithm = WeightedRoundRobinAlgorithm::new();
        let backends = vec![
            create_test_backend("backend1", 100),  // 权重100
            create_test_backend("backend2", 200),  // 权重200，应该被选中更多次
            create_test_backend("backend3", 100),  // 权重100
        ];
        let context = SelectionContext::default();

        let mut selections = HashMap::new();
        for _ in 0..12 {  // 选择12次，应该看到按权重分布
            if let Some(backend) = algorithm.select_backend(&backends, &context).await {
                *selections.entry(backend.config.id.clone()).or_insert(0) += 1;
            }
        }

        // backend2应该被选中最多次（权重最高）
        let backend2_count = selections.get("backend2").unwrap_or(&0);
        let backend1_count = selections.get("backend1").unwrap_or(&0);
        let backend3_count = selections.get("backend3").unwrap_or(&0);
        
        assert!(*backend2_count > *backend1_count, "backend2权重更高，应该被选中更多次");
        assert!(*backend2_count > *backend3_count, "backend2权重更高，应该被选中更多次");
    }

    #[tokio::test]
    async fn test_weighted_least_connections_algorithm() {
        let algorithm = WeightedLeastConnectionsAlgorithm::new();
        let backends = vec![
            create_test_backend("backend1", 200),  // 高权重
            create_test_backend("backend2", 100),  // 低权重
        ];
        
        // 给backend1添加连接，使其连接数更多
        backends[0].add_connection();
        backends[0].add_connection();
        backends[0].add_connection();
        
        let context = SelectionContext::default();
        let selected = algorithm.select_backend(&backends, &context).await;

        assert!(selected.is_some());
        // 虽然backend1连接数多，但权重高，计算后的比值可能仍然更优
        let selected_id = &selected.unwrap().config.id;
        assert!(selected_id == "backend1" || selected_id == "backend2");
    }

    #[tokio::test]
    async fn test_random_algorithm() {
        let algorithm = RandomAlgorithm::new();
        let backends = vec![
            create_test_backend("backend1", 100),
            create_test_backend("backend2", 100),
            create_test_backend("backend3", 100),
        ];
        let context = SelectionContext::default();

        let mut selections = std::collections::HashSet::new();
        for _ in 0..100 {  // 运行100次，应该选到所有后端
            if let Some(backend) = algorithm.select_backend(&backends, &context).await {
                selections.insert(backend.config.id.clone());
            }
        }

        // 随机算法应该能选到所有后端
        assert_eq!(selections.len(), 3, "随机算法应该能选择到所有健康的后端");
    }

    #[tokio::test]
    async fn test_least_response_time_algorithm() {
        let algorithm = LeastResponseTimeAlgorithm::new();
        let backends = vec![
            create_test_backend("backend1", 100),
            create_test_backend("backend2", 100),
        ];
        
        // 设置不同的响应时间
        backends[0].record_request(true, Duration::from_millis(500));  // 较慢
        backends[1].record_request(true, Duration::from_millis(100));  // 较快

        let context = SelectionContext::default();
        let selected = algorithm.select_backend(&backends, &context).await;

        assert!(selected.is_some());
        // 应该选择响应时间更短的backend2
        assert_eq!(selected.unwrap().config.id, "backend2");
    }

    #[tokio::test]
    async fn test_resource_aware_algorithm() {
        let algorithm = ResourceAwareAlgorithm::new();
        let mut backend1 = create_test_backend("backend1", 100);
        let mut backend2 = create_test_backend("backend2", 100);
        
        // 设置backend1的负载更高
        if let Ok(mut load) = backend1.current_load.write() {
            *load = 0.8;  // 80%负载
        }
        if let Ok(mut load) = backend2.current_load.write() {
            *load = 0.3;  // 30%负载
        }
        
        let backends = vec![backend1, backend2];
        let context = SelectionContext::default();
        let selected = algorithm.select_backend(&backends, &context).await;

        assert!(selected.is_some());
        // 应该选择负载更低的backend2
        assert_eq!(selected.unwrap().config.id, "backend2");
    }

    #[tokio::test]
    async fn test_algorithms_with_unhealthy_backends() {
        let backends = vec![
            create_test_backend("backend1", 100),
            create_test_backend("backend2", 100),
            create_test_backend("backend3", 100),
        ];
        
        // 设置backend2为不健康
        backends[1].set_healthy(false);

        let context = SelectionContext::default();
        let algorithms: Vec<Box<dyn LoadBalancingAlgorithm>> = vec![
            Box::new(RoundRobinAlgorithm::new()),
            Box::new(LeastConnectionsAlgorithm::new()),
            Box::new(RandomAlgorithm::new()),
        ];

        for algorithm in algorithms {
            for _ in 0..10 {
                if let Some(selected) = algorithm.select_backend(&backends, &context).await {
                    assert_ne!(selected.config.id, "backend2", 
                        "算法 {} 不应该选择不健康的后端", algorithm.name());
                }
            }
        }
    }

    #[tokio::test]
    async fn test_algorithms_with_no_healthy_backends() {
        let backends = vec![
            create_test_backend("backend1", 100),
            create_test_backend("backend2", 100),
        ];
        
        // 设置所有后端为不健康
        backends[0].set_healthy(false);
        backends[1].set_healthy(false);

        let context = SelectionContext::default();
        let algorithms: Vec<Box<dyn LoadBalancingAlgorithm>> = vec![
            Box::new(RoundRobinAlgorithm::new()),
            Box::new(LeastConnectionsAlgorithm::new()),
            Box::new(RandomAlgorithm::new()),
        ];

        for algorithm in algorithms {
            let selected = algorithm.select_backend(&backends, &context).await;
            assert!(selected.is_none(), 
                "当没有健康后端时，算法 {} 应该返回None", algorithm.name());
        }
    }

    #[tokio::test]
    async fn test_ip_hash_consistency() {
        let algorithm = IpHashAlgorithm::new();
        let backends = vec![
            create_test_backend("backend1", 100),
            create_test_backend("backend2", 100),
            create_test_backend("backend3", 100),
        ];

        let mut context = SelectionContext::default();
        context.client_ip = Some("192.168.1.100".to_string());

        // 同一IP多次选择应该得到相同结果
        let first_selection = algorithm.select_backend(&backends, &context).await;
        for _ in 0..10 {
            let selection = algorithm.select_backend(&backends, &context).await;
            assert_eq!(first_selection.as_ref().map(|b| &b.config.id), 
                      selection.as_ref().map(|b| &b.config.id),
                      "IP哈希算法对同一IP应该返回相同后端");
        }
    }

    #[test]
    fn test_backend_creation() {
        let backend = create_test_backend("test-backend", 150);
        
        assert_eq!(backend.config.id, "test-backend");
        assert_eq!(backend.config.weight, 150);
        assert_eq!(backend.connection_count(), 0);
        assert!(backend.is_healthy());
        assert_eq!(backend.success_rate(), 1.0);  // 默认成功率应该是1.0
    }

    #[test]
    fn test_backend_connection_management() {
        let backend = create_test_backend("test", 100);
        
        // 测试连接数管理
        backend.add_connection();
        backend.add_connection();
        assert_eq!(backend.connection_count(), 2);
        
        backend.remove_connection();
        assert_eq!(backend.connection_count(), 1);
        
        // 测试下溢保护（虽然这里使用了fetch_sub，可能会下溢到很大的值）
        backend.remove_connection();
        assert_eq!(backend.connection_count(), 0);
    }

    #[test]
    fn test_backend_request_recording() {
        let backend = create_test_backend("test", 100);
        
        // 测试请求记录
        backend.record_request(true, Duration::from_millis(100));
        backend.record_request(false, Duration::from_millis(200));
        backend.record_request(true, Duration::from_millis(150));
        
        assert_eq!(backend.success_rate(), 2.0 / 3.0);
        
        // 测试平均响应时间更新
        let avg_time = backend.avg_response_time.read().unwrap();
        assert!(*avg_time > Duration::from_millis(0), "平均响应时间应该大于0");
    }

    #[test]
    fn test_backend_health_management() {
        let backend = create_test_backend("test", 100);
        
        assert!(backend.is_healthy(), "新创建的后端应该是健康的");
        
        backend.set_healthy(false);
        assert!(!backend.is_healthy(), "设置为不健康后应该返回false");
        
        backend.set_healthy(true);
        assert!(backend.is_healthy(), "重新设置为健康后应该返回true");
    }

    #[test]
    fn test_backend_load_management() {
        let backend = create_test_backend("test", 100);
        
        // 测试初始负载
        let initial_load = *backend.current_load.read().unwrap();
        assert_eq!(initial_load, 0.0, "初始负载应该为0");
        
        // 测试负载设置
        backend.set_load(0.75);
        let current_load = *backend.current_load.read().unwrap();
        assert_eq!(current_load, 0.75, "负载设置后应该正确读取");
    }

    #[test]
    fn test_selection_context() {
        let mut context = SelectionContext::default();
        
        assert!(context.client_ip.is_none());
        assert!(context.session_id.is_none());
        assert!(context.request_headers.is_empty());
        assert!(context.custom_attributes.is_empty());
        
        context.client_ip = Some("192.168.1.1".to_string());
        context.session_id = Some("session-123".to_string());
        context.request_headers.insert("User-Agent".to_string(), "test-agent".to_string());
        context.custom_attributes.insert("region".to_string(), "us-west-1".to_string());
        
        assert_eq!(context.client_ip.as_ref().unwrap(), "192.168.1.1");
        assert_eq!(context.session_id.as_ref().unwrap(), "session-123");
        assert_eq!(context.request_headers.get("User-Agent").unwrap(), "test-agent");
        assert_eq!(context.custom_attributes.get("region").unwrap(), "us-west-1");
    }
}